package cn.itcast.gateway.fliter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @authar by xiecong
 * @Date 2022/2/12
 * @Description
 */
//顺序值
@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter {
    /**
     * @param exchange 封装了request response
     * @param chain 过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request请求参数
        ServerHttpRequest request = exchange.getRequest();
        //2.获取authorization参数
        String authorization = request.getQueryParams().getFirst("authorization");
        //3.判断参数是否为admin
        if ("admin".equals(authorization)){
            //4.如果是  就放行
            return chain.filter(exchange);
        }
        //5.如果不是 就拦截终止请求
        ServerHttpResponse response = exchange.getResponse();
        //响应指定状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //终止
        return response.setComplete();

    }
}
